package org.spal.locatario

import org.apache.commons.lang.math.NumberUtils

import grails.converters.JSON

import org.spal.Locatario;
import org.spal.Producto
import org.springframework.dao.DataIntegrityViolationException
import org.spal.Local

class ProductoController {
	static allowedMethods = [save: "POST", delete: "POST"]
	def springSecurityService

	def index() {
		render (view: "/locatario/menu/list")
	}

	def list() {
		def page = params.page as Integer
		def rows1 = params.rows as Integer

		if (page && rows1) {
			params.max = Math.min(rows1 ?: 10, 100)
			params.offset = (page-1) * rows1
		}

		def locatario = Locatario.get(springSecurityService.principal.id)

		def list = Producto.findAllByLocal(locatario.local,params)

		def count = Producto.count()

		render([total: count, rows: list] as JSON)
	}

	def show(Long id) {
		def productoInstance = Producto.get(id)
		if (!productoInstance) {
			render([success: false, error: message(code: 'default.not.found.message', args: [
					message(code: 'producto.label', default: 'Producto'),
					id
				])] as JSON)
			return
		}
		render productoInstance as JSON
	}

	def save() {

		def producto = (params.id) ? Producto.get(params.id) : new Producto ()

		if (!producto) {
			def error = [message: message(code: 'default.not.found.message', args: [
					message(code: 'producto.label', default: 'Producto'),
					params.id
				])]
			render([success: false, messages: [errors:[error]] ] as JSON)
			return
		}

		//		def version = NumberUtils.toLong(params.version)
		//		if (version != null) {
		//			if (producto.version > version) {
		//				producto.errors.rejectValue("version", "default.optimistic.locking.failure",
		//						[
		//							message(code: 'producto.label', default: 'Producto')] as Object[],
		//						"Another user has updated this Local while you were editing")
		//				render([success: false, messages: producto.errors] as JSON)
		//				return
		//			}
		//		}
		def locatario = Locatario.get(springSecurityService.principal.id)

		producto.nombre = params.nombre
		producto.descripcion = params.descripcion
		producto.precio = Float.parseFloat( params.precio)
		producto.fechaCreacion = new Date()
		producto.local = locatario.local

		def im = params.img
		if(!im.empty)
			producto.foto = request.getFile('img').inputStream.bytes

		if(params.habilitado)
			producto.habilitado = true
		else
			producto.habilitado =false

		if (!producto.save(flush: true)) {
			return
		}


		render([success: true] as JSON)
	}

	def delete(Long id) {
		def productoInstance = Producto.get(id)
		if (!productoInstance)
			render([success: false] as JSON)
		else {
			try {
				productoInstance.delete(flush: true)
				render([success: true] as JSON)
			}catch (DataIntegrityViolationException e) {
				render([success: false, erro: e.message] as JSON)
			}
		}
	}
}
